/**
 * useCountDown-倒计时
 */

import { useState, useEffect, useMemo } from "react";
import { calcTime, parseMs } from "@/utils/calc";
import { useLatest } from "@/hooks/useLatest";

export type DTime = Date | number | string | undefined;

interface Options {
  targetDate?: DTime;
  interval?: number;
  onEnd?: () => void;
}

export interface FormattedRes {
  days: number;
  hours: number;
  minutes: number;
  seconds: number;
  milliseconds: number;
}

function useCountDown(options?: Options) {
  const { targetDate, interval = 1000, onEnd } = options || {};
  const [time, setTime] = useState(() => calcTime(targetDate));
  const latestOnEnd = useLatest(onEnd);

  useEffect(() => {
    if (!targetDate) return setTime(0);

    setTime(calcTime(targetDate));

    const timer = setInterval(() => {
      const target = calcTime(targetDate);

      setTime(target);
      if (target === 0) {
        clearInterval(timer);
        latestOnEnd?.();
      }
    }, interval);

    return () => clearInterval(timer);
  }, [targetDate, interval, latestOnEnd]);

  const formattedRes = useMemo(() => {
    return parseMs(time);
  }, [time]);

  return [time, formattedRes] as const;
}

export default useCountDown;
